package com.code.leetcode.offer;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/7/30 12:32
 */
public class The13 {

    boolean[][] marked;
    int[][] direction = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    int k;
    int m, n;
    int num;

    public int movingCount(int m, int n, int k) {
        marked = new boolean[m][n];
        marked[0][0] = true;
        this.k = k;
        this.m = m;
        this.n = n;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                getToken(i, j);
            }
        }
        return num;
    }

    public void getToken(int i, int j) {
        int x = i;
        int y = j;
        if (i == 0 && j == 0) {
            num++;
            return;
        }
        int sum = 0;
        while (i % 10 != 0 || i / 10 != 0) {
            sum += i % 10;
            i = i / 10;
        }
        while (j % 10 != 0 || j / 10 != 0) {
            sum += j % 10;
            j = j / 10;
        }
        if (sum <= k && isValid(x, y)) {
            marked[x][y] = true;
            num++;
        }
    }

    private boolean isValid(int i, int j) {
        for (int k = 0; k < 4; k++) {
            int x = i + direction[k][0];
            int y = j + direction[k][1];
            if (x >= 0 && x < m && y >= 0 && y < n && marked[x][y]) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        The13 the13 = new The13();
        the13.movingCount(3, 2, 17);
    }
}
